package chenxi.proxy;

import lombok.NoArgsConstructor;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author bowen
 */
@NoArgsConstructor
public class CglibProxyHandler implements MethodInterceptor {

    private Object targetObject;

    public Object newProxy(Object obj) {
        this.targetObject = obj;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        proxyMethod();
        return method.invoke(targetObject, args);
    }

    private void proxyMethod() {
        System.out.println("代理方法被调用");
    }

}
